#region  == Copyright == 
// =====================================================================
//  Microsoft Consulting Services France - Aymeric Mouillé - 2013
//  Projet     : CRM Solution Management Tool
//  Fichier    : SolutionExport.cs (01/05/2013 11:06)
//  
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// =====================================================================
#endregion

namespace CRM.Solution.Management.Tool
{
    #region  == Using == 
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;

    using CRM.Solution.Manager.Properties;

    using Microsoft.Crm.Sdk.Messages;

    #endregion

    public partial class SolutionExport : Form
    {
        private MainForm MainForm;

        private SolutionItem SolutionItem;

        private readonly BackgroundWorker bgSolutionExport;

        private string SolutionExportPath;

        private ExportSolutionResponse ExportSolutionResponse;

        #region = Constructor =
        /// <summary>
        /// Initializes a new instance of the <see cref="SolutionExport" /> class.
        /// </summary>
        public SolutionExport(MainForm mainForm, SolutionItem solutionItem)
        {
            InitializeComponent();
            bgSolutionExport = new BackgroundWorker();
            bgSolutionExport.DoWork += bgSolutionExport_DoWork;
            bgSolutionExport.RunWorkerCompleted += BgSolutionExportOnRunWorkerCompleted;

            txtExportPath.Text = Settings.Default.DefaultExportPath;
            MainForm = mainForm;
            SolutionItem = solutionItem;
        }
        #endregion

        #region Btn Browse Click
        /// <summary>
        /// Handles the Click event of the btnBrowse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtExportPath.Text = folderBrowserDialog.SelectedPath;
            }
        }
        #endregion

        #region Btn Cancel Click
        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

        #region Btn Export Click
        /// <summary>
        /// Handles the Click event of the btnExport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="EventArgs" /> instance containing the event data.
        /// </param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            SolutionExportPath = txtExportPath.Text;
            ExportSolutionResponse = null;

            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
            exportSolutionRequest.SolutionName = SolutionItem.Name;
            exportSolutionRequest.Managed = chkManaged.Checked;
            exportSolutionRequest.ExportAutoNumberingSettings = chkExportAutoNumberingSettings.Checked;
            exportSolutionRequest.ExportCalendarSettings = chkExportCalendarSettings.Checked;
            exportSolutionRequest.ExportCustomizationSettings = chkExportCustomizationSettings.Checked;
            exportSolutionRequest.ExportEmailTrackingSettings = chkExportEmailTrackingSettings.Checked;
            exportSolutionRequest.ExportGeneralSettings = chkExportGeneralSettings.Checked;
            exportSolutionRequest.ExportIsvConfig = chkExportIsvConfig.Checked;
            exportSolutionRequest.ExportMarketingSettings = chkExportMarketingSettings.Checked;
            exportSolutionRequest.ExportOutlookSynchronizationSettings = chkExportOutlookSynchronizationSettings.Checked;
            exportSolutionRequest.ExportRelationshipRoles = chkExportRelationshipRoles.Checked;
            bgSolutionExport.RunWorkerAsync(exportSolutionRequest);
            Close();
        }
        #endregion

        #region Bg Solution Export Do Work
        /// <summary>
        /// Handles the DoWork event of the bgSolutionExport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="DoWorkEventArgs" /> instance containing the event data.
        /// </param>
        private void bgSolutionExport_DoWork(object sender, DoWorkEventArgs e)
        {
            MainForm.UpdateStripStatus("Exporting solution ...");
            try
            {
                ExportSolutionRequest exportSolutionRequest = (ExportSolutionRequest)e.Argument;
                ExportSolutionResponse = (ExportSolutionResponse)MainForm.OrganizationService.Execute(exportSolutionRequest);
            }
            catch (Exception ex)
            {
                MainForm.UpdateStripStatus("Error occured durring export : " + ex.Message, 100);
            }
        }
        #endregion

        #region Bg Solution Export On Run Worker Completed
        /// <summary>
        /// Bgs the solution export on run worker completed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="runWorkerCompletedEventArgs">
        /// The <see cref="RunWorkerCompletedEventArgs" /> instance containing the event data.
        /// </param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void BgSolutionExportOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            MainForm.UpdateStripStatus("Solution exported!", 100);
            string fileName = chkManaged.Checked ? string.Format("{0}_managed.zip", SolutionItem.Name) : string.Format("{0}_unmanaged.zip", SolutionItem.Name);
            string solutionFilePath = Path.Combine(SolutionExportPath, fileName);
            File.WriteAllBytes(solutionFilePath, ExportSolutionResponse.ExportSolutionFile);
            string argument = @"/select, " + solutionFilePath;
            Process.Start("explorer", argument);
        }
        #endregion
    }
}
